package async;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiFunction;

public class HandleDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(100);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int value = new Random().nextInt(100);
            int i = 1 / 0;
            System.out.println(value);
            return value;
        }, executor).handle(new BiFunction<Integer, Throwable, Integer>() {
            @Override
            public Integer apply(Integer integer, Throwable throwable) {
                int result = 1;
                if (throwable == null) {
                    result = integer * 10;
                    System.out.println(result);
                } else {
                    System.out.println(throwable.getMessage());
                }
                return result;
            }
        });
        try {
            Integer result = future.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (ExecutionException e) {
            e.printStackTrace();
            future.cancel(true);
        } finally {
            executor.shutdown();
        }
    }
}
